package learn.up.java1.anno;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class FilterDemo {

	public static void main(String[] args) {
		Filter filter = new Filter();
		filter.setId(10);//查询id为10的用户
		
		Filter filter2 = new Filter();
//模糊查询 姓名为john的用户		
		filter2.setName("john");
		
		Filter filter3 = new Filter();
		//查询城市为以下其中任意一个的
		filter3.setCity("NewYork,MIAMI,LosAngles");
		
		String sql1 = query(filter);
		System.out.println(sql1);
		String sql2 = query(filter2);
		System.out.println(sql2);
		String sql3 = query(filter3);
		System.out.println(sql3);
	}

	//返回一个sql语句
	private static String query(Filter filter) {
		StringBuilder stringBuilder = new StringBuilder();
		Class<? extends Filter> class1 = filter.getClass();
		if(class1.isAnnotationPresent(Table.class)) {
			Table annotation = class1.getAnnotation(Table.class);
			stringBuilder.append("select * from "+annotation.value()+" where 1=1");
			Field[] declaredFields = class1.getDeclaredFields();
			for (Field field : declaredFields) {
				if(field.isAnnotationPresent(Column.class)) {
					Column annotation2 = field.getAnnotation(Column.class);
					//得到字段名
					String value = annotation2.value();
					//通过反射得到字段值
					String name = field.getName();
					char charAt = name.charAt(0);
					String methodName = "get"+name.replace(charAt, (char)(charAt-32));
					try {
						Method method = class1.getMethod(methodName);
						Object invoke = method.invoke(filter);
						if(invoke != null) {
							if(name.equals("city")) {
								stringBuilder.append(" and "+value+" IN("+invoke+" )");
							} else if(name.equals("name")) {
								stringBuilder.append(" and "+value+" = '"+invoke+"'");
							} else{
								stringBuilder.append(" and "+value+" = "+invoke);
							}
							
						}
					} catch (NoSuchMethodException e) {
						e.printStackTrace();
					} catch (SecurityException e) {
						e.printStackTrace();
					} catch (IllegalAccessException e) {
						e.printStackTrace();
					} catch (IllegalArgumentException e) {
						e.printStackTrace();
					} catch (InvocationTargetException e) {
						e.printStackTrace();
					}
				}
			}
			return stringBuilder.toString();
		}
		return null;
	}

}
